const util = require('../../../utils/util.js');
const api = require('../../../config/api.js');
var app = getApp();
Page({
  data: {
    todayNum:0,
    coachNum:0,
    carNum:0,
    detail: {},
    page: 1,
    limit: 30,
    totalPages: 1,
    endFlag: false,
    loadingFlag: false,
    flag: 0,
    navbar_bgcolor: wx.getStorageSync('navbar_bgcolor'),
    activeCategoryId: 1,
    schoolId: 0,
    placeList: [], //场地信息
    classTypeList: [], //班型信息
    coachList: [], //教练信息,
    evalList: [],
    licensePlate: [], //车牌信息
    jd:'',//用户所在经度
    wd:'',//用户所在纬度
    longitude:'',//驾校经度
    latitude:'',//驾校纬度
    distance:'',//学员与驾校距离
  },

  onLoad: function (options) {
    console.log(options)
    var that = this;
    if(options.scene && options.scene !== ''){
      this.setData({
        schoolId: options.scene
      });
    }
    if(options.id && options.id !== ''){
      this.setData({
        schoolId: options.id
      });
    }
    this.getSchoolDetail();
    this.getStuEval();
    this.getlicensePlate();
    // 判断当前设备是否开启定位权限并给出提示
    // const systemSetting = wx.getSystemSetting()
    // if(systemSetting.locationEnabled === true){
    //   wx.showModal({  
    //     title: '提示',  
    //     content: '您还未开启定位权限！',  
    //     success (res) {  
    //       if (res.confirm) {  
    //         console.log('用户点击确定')  
    //       } else if (res.cancel) {  
    //         console.log('用户点击取消')  
    //       }  
    //     }  
    //   })
    // }
   
  },
  // 判断是否给小程序定位权限
  getPosition: function () {
    var that = this
    wx.getSetting({
      success(res) {
        //没给小程序定位权限时
        if (!res.authSetting['scope.userLocation']) {
          // wx.showModal({
          //   title: '提示',
          //   content: '您还没有启用定位权限，是否前往设置开启？',
          //   success(res) {
          //     if (res.confirm) {
          //       wx.openSetting({
          //         success(res) {
          //           if (res.authSetting['scope.userLocation']) {
          //             that.onLoad(); 
          //           } else {
          //             wx.showToast({
          //               title: '您还未开启定位权限',
          //               icon: 'none'
          //             });
          //           }
          //         }
          //       });
          //     } else if (res.cancel) {
          //       console.log(res.cancel);
          //       wx.showToast({
          //         title: '您还未开启定位权限',
          //         icon: 'none'
          //       });
          //     }
          //   }
          // });
        }
      },
      fail(err){
        // console.log(err)
        that.setData({
          distance :'-- '
        })
      }
    });
    // 获取设备所在的经纬度
    wx.getLocation({
          type: 'gcj02',
          success: function (res) {
            // console.log(res)
            that.setData({
              wd: res.latitude,
              jd: res.longitude
            })
            var juli = that.distance(that.data.jd,that.data.wd,that.data.detail.longitude,that.data.detail.latitude);
            if(juli === 'N'){
              that.setData({
                distance :'-- '
              })
            }else{
              that.setData({
                distance :juli
              })
            }
          },
          // 如果获取不到，可能是手机设备没开定位或其他原因，--
          fail(err){
            that.setData({
              distance :'-- '
            })
          }
    })
  },

   // 计算距离，经度，纬度，经度，纬度
  distance(lat1, lng1, lat2, lng2) {
    var that = this;
    let rad1 = lat1 * Math.PI / 180.0;
    let rad2 = lat2 * Math.PI / 180.0;
    let a = rad1 - rad2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(
      rad2) * Math.pow(
      Math.sin(b / 2), 2)));
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toString();
    s = s.substring(0, s.indexOf('.') + 2);
    // console.log('距离：', s);
    return s; //返回距离
},

  //获取教练车信息
  getlicensePlate: function () {
    let that = this;
    util.request(api.SchoollicensePlate, {
      schoolId: that.data.schoolId,
      page: that.data.page,
      limit: that.data.limit
    }).then(function (res) {
      that.setData({
        licensePlate: that.data.licensePlate.concat(res.data.list),
        totalPages: res.data.pages
      })
      // console.log(res.data.page+"第几页")
      // console.log(that.data.totalPages+"总页数")
    });
    wx.hideLoading();
  },
  getStuEval: function () {
    let that = this;
    util.request(api.schoolStuEvalUrl, {
      schoolId: that.data.schoolId
    }).then(function (res) {
      //console.log(JSON.stringify(res.data));
      that.setData({
        evalList: res.data
      })
    });
  },
  getSchoolDetail: function () {
    wx.showLoading({
      title: '加载中',
    });

    setTimeout(function () {
      wx.hideLoading()
    }, 2000);

    let that = this;
    util.request(api.SchoolDetailorModel, {
      id: that.data.schoolId
    }).then(function (res) {
      if (res.errno === 0) {
        //console.log(res.data.detail);
        //console.log(res.data.classTypeList);
        that.setData({
          detail: res.data.detail,
          placeList: res.data.placeList,
          classTypeList: res.data.classTypeList,
          coachList: res.data.coachList,
          todayNum :res.data.num,
          coachNum :res.data.coachNum,
          carNum :res.data.carNum
        });
      }
      wx.hideLoading();
      that.getPosition();
    });
  },


  tabClick: function (e) {
    this.setData({
      //activeIndex: e.currentTarget.id
      activeCategoryId: e.currentTarget.id
    });
  },
  callphone: function (e) {
    var that = this
    wx.makePhoneCall({
      phoneNumber: that.data.detail.phone, //仅为示例，并非真实的电话号码
      success: function () {
        console.log("电话拨打成功")
      },
      fail: function () {
        console.log("电话拨打失败")
        wx.showToast({
          title: '该驾校未设置联系方式',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  tobm: function (e) {
    /*var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name
    wx.navigateTo({
      url: '/pages/signup/add?jiaxiaoId=' + id + "&jiaxiaoName=" + name
    })*/
    var that = this
    var hasLogin = wx.getStorageSync("app.globalData.hasLogin");
    if (!hasLogin) {
      wx.navigateTo({
        url: '/pages/auth/login/login',
      })
    } else {
      /**保存一下当前选择的驾校信息 */
      wx.setStorageSync("schoolId", this.data.schoolId);
      wx.setStorageSync("schoolName", this.data.detail.name);
      //驾校满意率
      if (parseFloat(this.data.detail.satisfaction) < parseInt(95)) {
        wx.showModal({
          title: '提示',
          content: '该驾校满意率低于95%，请谨慎选择！',
          success: function (res) {
            if (res.confirm) {
              //console.log('用户点击确定')
              wx.navigateTo({
                url: '/pages/school/detail/ScModel?schoolId=' + that.data.schoolId + '&schoolName=' + that.data.detail.name,
              })
            } else if (res.cancel) {
              //console.log('用户点击取消')
            }
          }
        })
      } else {
        //console.log("我走了else");
        wx.navigateTo({
          //url: '/pages/signupV3/selectCarModel?schoolId='+this.data.schoolId+'&schoolName='+this.data.detail.name,
          url: '/pages/school/detail/ScModel?schoolId=' + this.data.schoolId + '&schoolName=' + this.data.detail.name,
        })
      }
      // wx.navigateTo({
      //   //url: '/pages/signupV3/selectCarModel?schoolId='+this.data.schoolId+'&schoolName='+this.data.detail.name,
      //   url: '/pages/school/detail/ScModel?schoolId='+this.data.schoolId+'&schoolName='+this.data.detail.name,
      // })
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.totalPages > this.data.page) {
      this.setData({
        page: this.data.page + 1
      });
      this.getlicensePlate();
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
  },
  onShareAppMessage: function (res) {},
  onPullDownRefresh: function () {},
  //地图跳转
  fnMap: function (e) {
    var location = e.currentTarget.dataset.location;
  },
  toNav: function (e) {
    var latitude = this.data.detail.latitude;
    var longitude = this.data.detail.longitude;
    var name = this.data.detail.name;
    var address = this.data.detail.address;
    wx.openLocation({ //?使用微信内置地图查看位置。
      latitude: Number(latitude), //要去地点的纬度
      longitude: Number(longitude), ///要去地点的经度-地址
      name: name, //
      address: address
    })
  }
})